package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/11 10:37
 * @Description:
 */
@RestController
public class TestFeign {
    private static Logger logger = LoggerFactory.getLogger(TestFeign.class);


    @GetMapping(value = "/get")
    public void doGet(String urlStr) {
        BufferedReader bufferedReader = null;
        HttpURLConnection connection = null;
        try {
            // 创建请求的地址
            URL realUrl = new URL(urlStr);
            //建立网络传输通道
            connection = (HttpURLConnection) realUrl.openConnection();
            // 设置请求头的信息
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(3 * 1000);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
            // do connection
            connection.connect();

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            String responseMsg = result.toString();
            logger.info("响应的结果：[{}]", JSONObject.toJSONString(responseMsg));

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送get方式的请求异常", e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                logger.error("关闭流异常 异常信息是", e);
            }
        }


    }

}
